/**
 * 数据库表格动态展示
 */

mini.parse();
var grid = new mini.DataGrid();
var tree;
var cols;
var grid_data;

var cTableName;
var searchCols=mini.get("searchCols");//获得下拉框的ID
var searchKey=mini.get("searchKey")
var formItem = parent.getFormItem().item;//菜单跳转后获取数据
console.log(formItem,'formItem');
//获取当前打开的页签
var nowOpenTab = parent.mainTab();
console.log(nowOpenTab,'当前打开的页签');
var menusFormTypes =  formItem.menusFormTypes;//表单/档案
var textField;
var complex_add_field;//复杂档案保存时增加的字段名称
var formId = formItem.formListId;
var menuId = formItem.id.match(/menuId(\S*)/)[1];
//分页控件

console.log(menuId);
var url = bootPATH + "../frame/frame1/pages/";      //路径前缀
var treeSelected;
var nodes;//所选节点的所有父节点
var condition;
var mTableName;
var clickStatus;                //双击状态
var formSh = localStorage.getItem("formShow");
console.log(formSh);
var formSh1=$.parseJSON(formSh);
console.log(formSh1);
console.log(formId,'formId');
//$('.table_name').html('<b>'+ formItem.formName +'</b>');//表名
// localStorage.clear();
// localStorage.removeItem("formShow");
var editBtnEl = mini.get('edit');
console.log(editBtnEl,'编辑按钮');
var fujian=[];
var pager;
init();
parent.activeChanged();//更新表格页
function getGridDate(pageIndex,callBack) {
    $.ajax({
        url: ajaxUrl + "/sqlAction/findsAll.do",
        type: "post",
        dataType: "json",
        data: {
            formListId: formId,
            PageIndex: pageIndex,
            PageSize: pager.getPageSize()
        },
        success: function (grid_data) {
            grid_data.data.forEach(function (item) {
                switch (item[cTableName + '_state']) {
                    case '0':
                        item[cTableName + '_state'] = '未提交';
                        break;
                    case '1':
                        item[cTableName + '_state'] = '已提交';
                        break;
                    case '2':
                        item[cTableName + '_state'] = '审批中';
                        break;
                    case '3':
                        item[cTableName + '_state'] = '终审';
                        break;
                    case '4':
                        item[cTableName + '_state'] = '驳回';
                        break;
                    case '5':
                        item[cTableName + '_state'] = '中止';
                        break;
                    case '6':
                        item[cTableName + '_state'] = '撤回';
                        break;
                    default:
                        item[cTableName + '_state'] = '未提交';
                }

            });
            grid.setData(grid_data.data);
            pager.set({"totalCount": grid_data.total})
            loadGrid();
            initBtn();
            if(callBack){
                callBack()
            }

        }
    })
}

function init() {

    $(".left").css({display: 'none'});
    $(".right").css("cssText", "width: 100% !important;overflow:auto;");

    //请求数据列表类型
    $.ajax({
        url : ajaxUrl + '/formList/findByFormId.do',
        type: "post",
        dataType: "json",
        data: {
            formListId: formId,
        },
        success: function (data){
            console.log(data);
            var type = data.data.formTypes;
            cTableName = data.data.cTableName;

            menusFormTypes = type;
            console.log(menusFormTypes,'档案类型')

            $("#gridField").css({
                height : document.body.clientHeight - 40
            });

            //加载列
            $.ajax({
                // url: ajaxUrl + "/formltems/findByFormListIdToStyle.do",
                url : ajaxUrl + "/formltems/findsAll.do",
                type: "post",
                dataType: "json",
                data: {
                    formListId: formId,
                    menuId: menuId
                },
                success: function(data){
                    console.log(data,'列');
                    for(var i=0;i<data.length;i++) {
                        if(data[i].tableType !='table' && data[i].tableType !='tab_table' && data[i].tableType !='tab' && data[i].tableType !='formname') {
                            cTableName = data[i].tableName;//获得主表名
                        }
                        if(i == 1) {
                            complex_add_field = data[i].cTreeStruct;
                        }
                    }
                    cols = data;//列数据
                    //cols.push(cols[cols.length-1])
                    console.log(cols,'列赋值数据');
                    var  selectcol=mini.clone(data);
                    console.log(selectcol);
                    //选择下拉框渲染表头
                    // var colss=data;
                    var  selectcols=selectcol.splice(1);
                    console.log(selectcols);
                    selectcols.unshift([]);
                    searchCols.setData(selectcols);
                    grid.set({
                        url: "",
                        style: "width:100%;height:100%;",
                        //id: "datagrid",
                        columns: cols,
                        pageSize: 50,
                        multiSelect: true,
                        allowResize: true,
                        allowCellEdit: false,
                        allowCellSelect: true,
                        cellEditAction: "cellclick",
                        allowRowSelect: true,
                        // showPager: true,
                        editNextOnEnterKey: true,
                        editNextRowCell: true
                    });
                    grid.render(document.getElementById("gridField"));
                    pager = grid.getBottomPager();
                    getGridDate(1,function(){
                        //	获取主子表关系
                        $.ajax({
                            url: ajaxUrl + "/tableClass/tableRelations.do",
                            // url: "http://192.168.31.65:8080/DSMP/tableClass/tableRelations.do",
                            type: "post",
                            // dataType: "json",
                            traditional: true,
                            data: {
                                formId: formId
                            },
                            success: function(dataMT){
                                console.log(dataMT,'主子表关系');
                                mTableName = dataMT.mTableName;
                            },
                            error : function(data){
                            }
                        });
                    })




                },
                error : function(data){
                }
            });

        },
        error: function (data){
            console.log('失败');
        }
    })
}
function loadGrid() {

    //复杂档案
    if(menusFormTypes == 'complex') {
        $(".left").css({display: 'block'});
        $(".right").css("cssText", "width: calc(100% - 207px)!important;overflow:auto;");

        tree = mini.get("tree");
        //加载树形
        $.ajax({
            url: ajaxUrl + "/formltems/formTree.do?",
//        	url: "http://192.168.31.65:8080/bpm/formltems/formTree.do?",
            type: "post",
            dataType: "json",
            data: {
                formListId: formId
            },
            success: function(treeData){
                console.log(treeData,'treeData');
                $.ajax({
                    url: ajaxUrl + "/formList/findByFormListId.do?formListId="+formId,
                    type: "post",
                    dataType: "json",
                    success: function(textFieldData){
                        console.log(textFieldData.data);
                        console.log(typeof textFieldData.data);

                        // var aaa=JSON.parse(textFieldData.data)
                        // console.log(aaa);
                        // textField = aaa.selecteds[0].cTableField;

                        condition = $.parseJSON(textFieldData.data).selecteds[0].cTableName;
                        console.log(textField,'树形textField')
                        tree.set({
                            textField: 'name'
                        });
//                        tree.loadList(treeData, "id", "parent_level");
//                        console.log(tree.getData());
                        tree.setData(treeData);
                        var clickNodeFlag = 0;
                        tree.on("nodeselect", function (e) {
                            console.log(e);
                            clickNodeFlag++;
                            treeSelected = e.selected;
                            console.log(treeSelected);
                            nodes = tree.getAncestors(treeSelected);
                            nodes.push(treeSelected);
                            $.ajax({
                                url: ajaxUrl + "/formltems/selectArchives.do",
//                                url:"http://192.168.31.65:8080/bpm/formltems/selectArchives.do",
                                type: "post",
                                dataType: "json",
                                data: {
                                    formListId: formId,
                                    condition: e.node.tabName,
                                    conValue: e.node.id
                                },
                                success: function(data){
                                    console.log(data);
                                    grid_data = data.data;
                                    grid.setData(grid_data);
                                },
                                error : function(data){
                                }
                            });
                        })
                    },error : function(data){
                    }
                });
            },
            error : function(data){
            }
        });

    }else if(menusFormTypes == 'treeFile') {//单个树形

        $(".left").css({display: 'block'});
        $(".right").css("cssText", "width: calc(100% - 207px)!important;overflow:auto;");

        tree = mini.get("tree");
        //加载树形
        $.ajax({
            url: ajaxUrl + "/sqlAction/findsAll.do",
            type: "post",
            dataType: "json",
            data: {
                formListId: formId,
                menuId: menuId
            },
            success: function(treeData){
                console.log(treeData,'treeData');
                tree.set({
                    textField: cTableName + '_name'
                });
                tree.loadList(treeData, cTableName + "_id", "parent_level");
                tree.on("nodeselect", function(e) {
                    console.log(cTableName);
                    console.log(e.selected,'dwadwadwa');
                    var cba=e.selected[cTableName + '_id'];
                    console.log(cba);

                    $.ajax({
                        url: ajaxUrl + "/sqlAction/findByParentLevel.do",
                        type: "post",
                        dataType: "json",
                        data: {
                            tableName: cTableName,
                            parentLevel: cba
                        },
                        success: function(data){
                            console.log(data);
                            grid_data = data.data;
                            grid.setData(grid_data);
                        },error : function(data){
                        }
                    });
                });
            },
            error : function(data){

            }
        });

    }else if(menusFormTypes == 'other'){//暂时不用
        $(".right").css({display: 'none'});
        $(".left").css("cssText", "width: 100% !important;overflow:auto;");
        tree = mini.get("tree");
        $.ajax({
            url: ajaxUrl + "/formltems/findFormSource.do",
//            url:"http://192.168.31.65:8080/bpm/formltems/findFormSource.do",
            type: "post",
            dataType: "json",
            data: {
                formListId: formId,
                menuId: menuId
            },
            success: function (data) {
                console.log(data, '数据');
                tree.set({
                    textField: 'name'
                });
                tree.loadList(data, "id", "parent_level");

                // 加载表格所有数据
                $.ajax({
                    url: ajaxUrl + "/formltems/findFormSource.do",
                    //url:"http://192.168.31.65:8080/bpm/formltems/findFormSource.do",
                    type: "post",
                    dataType: "json",
                    data: {
                        formListId: formId,
                        menuId: menuId
                    },
                    success: function (grid_data) {
                        console.log(grid_data, '数据');
                        grid.setData(grid_data);
                    },
                    error: function (data) {
                    }
                });
            },
            error: function (data) {
            }
        });
    }else {
        //$(".left").css({width: 0});
        $(".left").css({display: 'none'});
        $(".right").css("cssText", "width: 100% !important;overflow:auto;");
        //数据
        $.ajax({
            //url: ajaxUrl + "/sqlAction/findsAll.do",
            url: ajaxUrl + "/sqlAction/findsAll.do",
            //url:"http://192.168.31.65:8080/bpm/formltems/findFormSource.do",
            type: "post",
            dataType: "json",
            data: {
                formListId: formId,
                menuId: menuId,
                PageIndex: 1,
                PageSize: pager.getPageSize()
            },
            success: function (data) {
                console.log(data, '数据');
                grid_data = data;
                grid_data.forEach(function (item) {
                    switch (item[cTableName+'_state']) {
                        case '0':
                            item[cTableName+'_state'] = '未提交';
                            break;
                        case '1':
                            item[cTableName+'_state'] = '已提交';
                            break;
                        case '2':
                            item[cTableName+'_state'] = '审批中';
                            break;
                        case '3':
                            item[cTableName+'_state'] = '已终审';
                            break;
                        case '4':
                            item[cTableName+'_state'] = '已驳回';
                            break;
                        case '5':
                            item[cTableName+'_state'] = '已中止';
                            break;
                        case '6':
                            item[cTableName+'_state'] = '已撤回';
                            break;
                        default:
                            item[cTableName+'_state'] = '未提交';
                    }

                });
                grid.setData(grid_data);
            },
            error: function (data) {
            }
        });
    }
}

//分页
grid.on("beforeload", function (e) {
    //阻止本来的翻页功能
    e.cancel = true;
    //当前页码
    var cunrrentPageIndex = grid.getPageIndex();
    //点击按钮之后的页码
    var pageIndex = e.data.pageIndex;
    //设置当前页数值
    pager.set({"pageIndex": pageIndex});
    //数据总数
    //var pageCount = pubPageCount;
    pager.set({"pageIndex": pageIndex});
    debugger
    //httpRequest({},pageIndex + 1, pager.getPageSize());
    getGridDate(pageIndex + 1,null)

});
function httpRequest(PageIndex, PageSize){

}
var formShow;
//新增 跳转到表单展示页
function addFormShow() {
    $.ajax({
        url: ajaxUrl + "/Coding/addCoding.do",
//            url:"http://192.168.31.65:8080/bpm/formltems/findFormSource.do",
        type: "post",
        dataType: "json",
        data: {
            formId: formId
        },
        success: function (data) {
            console.log(data, '数据');
            localStorage.setItem("coding",JSON.stringify(data));
            formShow = {
                action: 'add',
                formListId: formId,
                cTableName: cTableName,
                menuId: menuId,
                edit_data: [],
                menusFormTypes: menusFormTypes,
                treeSelected: treeSelected,
                textField: textField,
                complex_add_field: complex_add_field,
                nodes: nodes
            };
            // document.cookie='';
            // document.cookie= "items="+JSON.stringify(formShow)+";path=/";
            // localStorage.clear();
            // localStorage.removeItem("formShow");
            console.log(formShow);
            localStorage.setItem("formShow",JSON.stringify(formShow));

            var item = {
                iconCls: "fa fa-desktop",
                // id: formId,
                text: "表单展示",
                url: "../pages/formDesign/formTemplate2.html"
            };
            parent.activeTab(item);//与父页面通信
        },
        error: function (data) {
        }
    });
}
//双击查看单据
grid.on('rowdblclick',editFormShow);
//编辑 跳转到表单展示页
function editFormShow(clickType) {
    console.log(clickType,'双击还是单击');
    var row = grid.getSelecteds();
    console.log(row);
    //判断是否选中(单选)
    if(row.length == 1){
        $.ajax({
            url: ajaxUrl + "/activitiTaskController/findStateById.do",
            data: {
                id: row[0][cTableName + '_id'],
                cTableName: cTableName
            },
            type: 'post',
            success: function (data) {
                state = data.state[0][cTableName + '_state'];
                //如果是编辑按钮打开
                if(clickType == 'btn'){
                    //点击状态为单击按钮
                    clickStatus = 'btn';
                    if (state == 1 || state == 2 || state == 3) {
                        mini.alert('单据审核中 无法修改');
                    } else {
                        editDataHandle(row[0]);
                    }
                    //如果是双击打开
                }else{
                    //点击状态为双击赋值
                    clickStatus = clickType.type;
                    editDataHandle(row[0]);
                }
            }
        })
    }else{
        mini.alert('请选择且只选择一条单据');
    }
}
//编辑/查看时数据处理
function editDataHandle(rowData){
    //请求编辑数据的参数
    var obj = {
        cTableName: cTableName,// 主表的名称
        formId: formId,// 表单id
        id: rowData[mTableName + '_id'],
    };
    if(rowData.mTableId == undefined) {
        obj.mTableId = rowData.id;
    }else {
        obj.mTableId = rowData.mTableId;
    }
    //添加缓存数据，子页面获取值
    localStorage.setItem("obj",JSON.stringify(obj));
    //请求编辑数据,并跳转页面
    $.ajax({
        //url: "http://192.168.31.65:8080/bpm/formltems/formByMtableId.do",
        url: ajaxUrl + "/sqlAction/findById.do",
        type: "post",
        dataType: "json",
        contentType : "application/json",
        data: JSON.stringify(obj),
        success: function (data) {
            console.log(data, '获得编辑的数据');
            formShow = {//表单展示页
                action: 'edit',
                formListId: formId,
                cTableName: cTableName,
                menuId: menuId,
                edit_data: data[0],
                treeSelected: treeSelected,
                textField: textField,
                complex_add_field: complex_add_field,
                formState: rowData[cTableName + '_state'],
                clickStatus: clickStatus
            };
            // document.cookie='';
            // document.cookie= "items="+JSON.stringify(formShow)+";path=/";
            // localStorage.clear();
            // localStorage.removeItem("formShow");
            localStorage.setItem("formShow",JSON.stringify(formShow));
            var formSh = localStorage.getItem("formShow");
            var  formSh=$.parseJSON(formSh);
            console.log(formSh);
            var item = {
                iconCls: "fa fa-desktop",
                // id: formId,
                text: "表单展示",
                url: "../pages/formDesign/formTemplate2.html"
            };
            parent.activeTab(item);//与父页面通信
        },
        error: function (data) {
        }
    });
}
//删除行
function removeRow() {
    mini.confirm("确定删除？", "确定？",
        function (action) {
            if (action == "ok") {
                var rows = grid.getSelecteds();
                console.log(rows,'列');
                //处理数据
                var idTableNameArr = [];
                rows.forEach(function (item) {
                    var obj = {};
                    obj.cTableName = cTableName;
                    obj.id = item[cTableName + '_id'];
                    idTableNameArr.push(obj);
                });
                console.log(idTableNameArr,'拼接id和表名的数据');
                $.ajax({
                    url : ajaxUrl+"/activitiTaskController/findStateById.do",

                    data: {
                        id:rows[0][cTableName+'_id'],
                        cTableName:cTableName
                    },
                    type : 'post',
                    success: function(data){
                        console.log(data);
                        state = data.state[0][cTableName+'_state'];
                        console.log(data.state);
                        console.log(state);

                        if(state == 1||state==2){
                            mini.alert('单据审核中 无法删除');
                        } else if (state==3){
                            mini.alert('单据已终审 无法删除');
                        } else{
                            console.log('能删除');
                            var rows = grid.getSelecteds();
                            console.log(rows,'列');

                            if (rows.length > 0) {
                                var del_data = [];

                                //为删除的数据添加所属表名
                                for(var i=0;i<rows.length;i++) {
                                    for(var item in rows[i]) {
                                        for(var j=0;j<cols.length;j++) {
                                            if(cols[j].hasOwnProperty("tableName")) {
                                                if(rows[i].mTableId == undefined) {
                                                    del_data.push({
                                                        cTableName: cols[j].tableName,
                                                        mTableId: rows[i].id,
                                                        id: rows[i][mTableName + '_id'],
                                                        formId: formId
                                                    });
                                                }else {
                                                    del_data.push({
                                                        cTableName: cols[j].tableName,
                                                        mTableId: rows[i].mTableId,
                                                        id: rows[i][mTableName + '_id'],
                                                        formId: formId
                                                    });
                                                }
                                            }
                                        }
                                    }
                                }
                                del_data = unique(del_data);//数组去重
                                console.log(del_data);
                                // console.log(JSON.stringify(del_data));

                                $.ajax({
                                    url: ajaxUrl + "/sqlAction/delete.do",
                                    //url:"http://192.168.31.65:8080/bpm/formltems/deleteFormSource.do",
                                    type: "post",
                                    dataType: "json",
                                    contentType : "application/json",
                                    data: JSON.stringify(del_data),
                                    success: function(data){
                                        console.log(data,'数据');
                                        if(data.state=="error"){
                                            mini.alert(data.message);
                                        }else{
                                            refresh();
                                            // init();
                                        }


                                        // console.log(grid.getData());
                                    },
                                    error : function(data){
                                        mini.alert('删除失败')
                                    }
                                });

                            }else {
                                mini.alert('请选择需要删除的行');
                            }

                        }

                    },
                    error: function(data){
                        console.log(data);
                    }
                });
            }
        }
    );
}

//数组对象去重（去除完全重复的对象）
function unique(arr) {
    var arrResult = [];
    for(var i=0;i<arr.length;i++){
        arr[i] = JSON.stringify(arr[i]);//对象转成字符串的方法
        arrResult.push(arr[i]);//重新填装成一个《字符串》组成的数组
    }
    arr = [];//清空原来的数据
    arrResult = $.unique(arrResult); // 去掉重复的字符串
    for(var j=0;j<arrResult.length;j++){
        arrResult[j] = JSON.parse(arrResult[j]);// 重新给字符串转换成对象
        arr.push(arrResult[j]);//重新填装成一个《对象》组成的数组
    }
    // console.log(arr,'组装后的数组');//看一下组装后的数组
    return arr;
}

// function search() {
//     var search_key = mini.get("search_key").getValue();
//     // grid.load({ key: search_key });
// }

function onKeyEnter(e) {
    search();
}

//获取表格数据
function refresh() {

    //window.location.reload();
    init();
    $.ajax({
        url: ajaxUrl + "/formltems/findFormSource.do",
        type: "post",
        dataType: "json",
        data: {
            formListId: formId,
            menuId: menuId
        },
        success: function(data){
            console.log(data,'数据');
            grid_data = data;
            grid.setData(grid_data);
        },
        error : function(data){
            mini.alert('获取失败')
        }
    });
}

//初始化按钮
function initBtn() {

    $.ajax({
        type : 'post',
        // url : ajaxUrl+"/buttons/findByState.do",
        url : ajaxUrl+"/buttons/findByMenuIdAndUserInfo.do?menuId="+menuId,
        //url : "http://192.168.31.65:8080/bpm/buttons/findByState.do",
        dataType : 'json',
        success : function (data) {
            console.log(data,'buttons');
            //如果请求成功
            if(data.state == 'success'){
                var btnArr = data.data;
                $('#btns').html("");
                //循环赋值
                btnArr.forEach(function (btnItem) {
                    //var editStr = `<a class="mini-button" id="${btnItem.elId}" style="display:inline-block;margin-right:3px" iconCls="${btnItem.buttonImg}" onclick="${btnItem.eventName}" >${btnItem.buttonText}</a>`;
                    var editStr = '<a class="mini-button" id="' + btnItem.elId + '" style="display:inline-block;margin-right:3px" iconCls="' + btnItem.buttonImg + '" onclick="' + btnItem.eventName + '" >' + btnItem.buttonText + '</a>';
                    //添加到页面
                    // $('#btns').remove(editStr);

                    $('#btns').append(editStr);
                    //转化为miniui样式
                    mini.parse();
                });

            }
            // for(var i=0;i<data.data.length;i++) {
            //     switch (data.data[i].buttonText) {
            //         case '增加':
            //             $("#add").css({display:"inline-block"});break;
            //         case '修改':
            //             $("#edit").css({display:"inline-block"});break;
            //         case '删除':
            //             $("#remove").css({display:"inline-block"});break;
            //         case '提交':
            //             $("#submit").css({display:"inline-block"});break;
            //     }
            // }
//            $.ajax({
//                type : 'post',
//                // url : ajaxUrl+"/formltems/printFile.do?formListId="+formId,
//                url : "http://192.168.31.65:8080/bpm/formltems/printFile.do?formListId="+formId,
//                dataType : 'json',
//                success : function (data) {
//                    console.log(data,'printValue');
//                    mini.get('printText').setData(data);
//                },
//                error : function (message) {
//
//                }
//            });
        },
        error : function (message) {

        }
    })

}
//提交
function onSubmit(){
    var row = grid.getSelected();
    console.log(row);
    console.log(row[mTableName+'_id']);
    console.log(row[mTableName+'_single_person']);
    var state;
    if(row){
        $.ajax({
            url : ajaxUrl+"/activitiTaskController/findStateById.do",

            data: {
                id:row[mTableName+'_id'],
                cTableName:cTableName
            },
            type : 'post',
            success: function(data){
                console.log(data);
                state = data.state[0][cTableName+'_state'];
                console.log(data.state);
                console.log(state);


                if(state == 1||state==2|| state==3){
                    mini.alert('不能重复提交');
                }else{
                    console.log('能提交');

                    $.ajax({
                        url : ajaxUrl+"/activitiTaskController/startApply.do",

                        data: {
                            taskId: row[mTableName+'_id'],
                            formId: formId,
                            userName:row[mTableName+'_single_person']
                        },
                        type : 'post',
                        success: function(data){

                            mini.alert(data.msg);
                            console.log(data, '新增提交返回');
                            formShow = {//表单展示页
                                action: 'edit',
                                formListId: formId,
                                cTableName: cTableName,
                                menuId: menuId,
                                edit_data: data[0],
                                treeSelected: treeSelected,
                                textField: textField,
                                complex_add_field: complex_add_field
                            };
                            // document.cookie='';
                            // document.cookie= "items="+JSON.stringify(formShow)+";path=/";
                            // localStorage.clear();
                            // localStorage.removeItem("formShow");
                            localStorage.setItem("formShow",JSON.stringify(formShow));
                            var formSh = localStorage.getItem("formShow");
                            var  formSh=$.parseJSON(formSh);
                            console.log(formSh);
                            var taskId = data.taskId;
                            var msg = '消息有新任务|' + userInfoObj.userId+'|'+data.userInfo.userId;

                            console.log(msg, '要发送的消息');
                            send(msg);

                        },
                        error: function(data){
                            console.log(data);
                        }
                    })

                }

            },
            error: function(data){
                console.log(data);
            }
        });
        // console.log(state,'状态');

    }else{
        mini.alert('请选择需要提交的数据');
    }
}

function onPrint() {
//	top.location.href="//www.baidu.com";
//     mini.get("printText").getSelected();
//     var data = {
//         fileRout: mini.get("printText").getSelected().fileRout,
//         datasource: grid.getSelecteds()
//     }
//     localStorage.setItem('printData',JSON.stringify(data));
//     window.open('../../../../printingH5.html','_blank');
    //var row = grid.getRow(rowIndex);
    var row = grid.getSelected();
    if (row) {
        $.ajax({
            url: ajaxUrl + '/printTemplate/findModelIdByFormListId.do',
            type: 'POST',
            data: {
                formListId: formId
            },
            success: function (data) {
                console.log(data);
                row.pageType = '打印';
                row.modelNumId = data.modelId;
                row.vouchId = data.vouch.id;
                row.cTableName = cTableName;
                row.cTemplateName = data.vouch.cTemplateName;
                console.log(row);
                localStorage.setItem('row',JSON.stringify(row));
                mini.open({
                    url: bootPATH + "../frame/frame1/pages/DesignerPrint/PrintView.html",
                    title: "打印预览==>"+row.cTemplateName,
                    width: 900,
                    height: 1000,
                    showMaxButton:true,
                    loadOnRefresh:false,
                    ondestroy: function (action) {  //弹出页面关闭前
                        if (action == "ok") {       //如果点击“确定”
                            var iframe = this.getIFrameEl();
                            row=iframe.contentWindow.thiseditrow;
                            grid.reload();
                        }
                    }
                });
            },
            error: function (data) {
                mini.alert('失败');
            }
        })

    }
}

function onfindsAll() {
    var searchObj = {
        formListId: formId,
        cTableName: cTableName,
        PageIndex: PageIndex,
        PageSize: PageSize
    };
    var searchStr = JSON.stringify(searchObj);
    $.ajax({
        url: ajaxUrl + "/formltems/findsAll.do",
        type: "post",
        //dataType: "json",
        data: searchStr,
        contentType : "application/json",
        success: function(data){
            console.log(data,'数据');
            grid_data = data.data;
            grid.setData(grid_data);
        },
        error : function(data){
            mini.alert('获取失败')
        }
    });
}
//查看明细
function byId(){
    var row = grid.getSelected();
    if(row){
        $(".left").css({display: 'none'});
        $(".right").css("cssText", "width: 100% !important;overflow:auto;");
        //请求数据列表类型
        $.ajax({
            url : ajaxUrl + '/formList/findByFormId.do',
            type: "post",
            dataType: "json",
            data: {
                formListId: formId,
            },
            success: function (data){
                console.log(data);
                var type = data.data.formTypes;
                cTableName = data.data.cTableName;
                menusFormTypes = type;
                console.log(menusFormTypes,'档案类型')

                $("#gridField").css({
                    height : document.body.clientHeight - 100
                });

                //加载列
                $.ajax({
                    url: ajaxUrl + "/formltems/findByFormListIdToStyle.do",
                    // url : ajaxUrl + "/formltems/findsAll.do",
                    type: "post",
                    dataType: "json",
                    data: {
                        formListId: formId,
                        menuId: menuId
                    },
                    success: function(data){
                        //console.log(data,'列');
                        for(var i=0;i<data.length;i++) {
                            if(data[i].tableType !='table' && data[i].tableType !='tab_table' && data[i].tableType !='tab' && data[i].tableType !='formname') {
                                cTableName = data[i].tableName;//获得主表名
                            }
                            if(i == 1) {
                                complex_add_field = data[i].cTreeStruct;
                            }
                        }
                        cols = data;//列数据
                        //cols.push(cols[cols.length-1])
                        console.log(cols,'列赋值数据');
                        grid.set({
                            url: "",
                            style: "width:100%;height:100%;",
                            // id: "datagrid",
                            columns: cols,
                            multiSelect: true,
                            allowResize: true,
                            allowCellEdit: false,
                            allowCellSelect: true,
                            cellEditAction: "cellclick",
                            allowRowSelect: true,
                            //showPager: true,
                            editNextOnEnterKey: true,
                            editNextRowCell: true
                        });
                        grid.render(document.getElementById("gridField"));

                        // 加载表格所有数据
                        $.ajax({
                            // url: ajaxUrl + "/sqlAction/findAll.do",
                            url: ajaxUrl + "/sqlAction/findsAll.do",
                            //url:"http://192.168.31.65:8080/bpm/formltems/findFormSource.do",
                            type: "post",
                            dataType: "json",
                            data: {
                                formListId: formId,
                                menuId: menuId
                            },
                            success: function (grid_data) {
                                // console.log(grid_data[0].DetailsOffsetReserveGoods, '数据');
                                // grid.setData(grid_data[0].DetailsOffsetReserveGoods);

                                loadGrid();
                                initBtn();

                                //	获取主子表关系
                                $.ajax({
                                    url: ajaxUrl + "/tableClass/tableRelations.do",
                                    // url: "http://192.168.31.65:8080/DSMP/tableClass/tableRelations.do",
                                    type: "post",
                                    // dataType: "json",
                                    traditional: true,
                                    data: {
                                        formId: formId
                                    },
                                    success: function(dataMT){
                                        console.log(dataMT,'主子表关系');
                                        mTableName = dataMT.mTableName;
                                    },
                                    error : function(data){
                                    }
                                });

                            },
                            error: function (data) {
                            }
                        });

                    },
                    error : function(data){
                    }
                });

            },
            error: function (data){
                console.log('失败');
            }
        })
    }else{
        mini.alert('请选择一条数据查看');
    }



//撤销
}
function oncanCel() {
    var row = grid.getSelecteds();
    console.log(row);

    if (row.length > 1) {
        mini.alert('不能对多条数据进行撤销');
    } else if (row.length == 0) {
        mini.alert('请选择需要撤销的行');
    } else {
        $.ajax({
            url: ajaxUrl + '/activitiTaskController/cancelTask.do',
            type: 'POST',
            data: {
                cTableName:cTableName,
                formId: formId,
                id: row[0][mTableName + '_id']
            },
            //contentType : "application/json",
            success: function (data) {
                console.log(data);
                mini.alert(data.data);
            },
            error: function (data) {
                console.log(data);
                mini.alert("失败");
            }
        })
    }
}

//栏目设置
function  columnSet() {

    console.log(formId);
    console.log(menuId);
    mini.open({
        url: url +"dbshowGridson.html",
        title: "栏目设置", width: 800, height: 600,
        onload: function () {
            var iframe = this.getIFrameEl();
            var data = {formId:formId, menuId:menuId};
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {

        }
    });
}
//查询
function search() {
    var colVal = searchCols.getValue();
    var keyVal = searchKey.getValue();
    if(colVal){
        if(keyVal){
            var searchObj = {
                colVal: colVal,
                keyVal: keyVal,
                cTableName: cTableName,
                formListId: formId
            };
            var jsonStr = JSON.stringify(searchObj);
            $.ajax({
                url: ajaxUrl + '/sqlAction/findFilter.do',
                type: 'POST',
                data: jsonStr,
                contentType : "application/json",
                success: function (data) {
                    console.log(data);
                    //无树
                    grid.setData(data);

                },
                error: function (data) {
                    mini.alert('请求失败')
                }
            })
        }else{
            mini.alert('请选择需要搜索的项');
        }
    }else{
        mini.alert('请选择需要查询的列')
    }
}
function viewRecord() {
    var row = grid.getSelected();
    var rows= grid.getSelecteds();
    console.log(rows.length);

    console.log(formId);
    if (rows.length > 1) {
        mini.alert('不能对多条数据进行查看');
    } else if (rows.length == 0) {
        mini.alert('请选择需要查看的行');
    } else {
        var formId=row[cTableName + '_id'];

        mini.open({
            url: url + "dbshowGridson2.html",
            title: "查看流程图", width: 800, height: 700,
            onload: function () {
                var iframe = this.getIFrameEl();

                var data = {formId: formId, cTableName: cTableName};

                iframe.contentWindow.SetData(data);

            },
            ondestroy: function (action) {
                httpRequest();
            }
        });
    }
}
//附件详情
function annex() {
    var row = grid.getSelecteds();

    fujian.push(cTableName);
    fujian.push(row[0][cTableName + '_id']);
    mini.open({

        url:url +"Attachmentdetails.html",
        title: "附件详情", width: 800, height: 600,
        onload: function () {
            var iframe = this.getIFrameEl();
            var data = {
                fujian:fujian
            };
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {

        }

    })
}
//表单导出Execl
function Exproto() {
    var row = grid.getSelecteds();
    console.log(cTableName);
    var rowList = [];
    for (var i = 0; i < row.length; i++) {
        rowList.push(row[i][cTableName+"_id"])
    }
    console.log("rowList"+rowList);
    location.href = encodeURI(ajaxUrl + "/sqlAction/Export.do?rowList="+rowList+"&cTableName="+cTableName);
}
function Exproto() {
    var row = grid.getSelecteds();
    console.log(cTableName);
    var rowList = [];
    for (var i = 0; i < row.length; i++) {
        rowList.push(row[i][cTableName+"_id"])
    }
    console.log("rowList"+rowList);
    location.href = encodeURI(ajaxUrl + "/sqlAction/Export.do?rowList="+rowList+"&cTableName="+cTableName);
}